<template>
  <div class="wrapper">
    <header>
      <p>修改地址</p>
    </header>
    <div class="content">
      <ul>
        <li>
          <p>联系人：</p>
          <input type="text" placeholder="请输入姓名" v-model="address.contactName">
        </li>
        <li>
          <p>性别：</p>
          <div class="sex">
            <label>
              <input type="radio" name="sex" value="1" v-model="address.contactSex">
              先生
            </label>
            <label>
              <input type="radio" name="sex" value="0" v-model="address.contactSex">
              女士
            </label>
          </div>
        </li>
        <li>
          <p>手机号：</p>
          <input type="tel" placeholder="请输入手机号" v-model="address.contactTel">
        </li>
        <li>
          <p>送餐地址：</p>
          <input type="text" placeholder="请输入送餐地址" v-model="address.address">
        </li>
      </ul>
      <button class="save-btn" @click="editUserAddress">保存地址</button>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import request from '@/utils/request'
import { ElMessage } from 'element-plus'

const router = useRouter()
const route = useRoute()

const address = ref({
  daId: route.query.daId,
  contactName: '',
  contactSex: 1,
  contactTel: '',
  address: ''
})

// 获取地址信息
const loadAddress = async () => {
  try {
    const token = sessionStorage.getItem('token')
    if (!token) {
      ElMessage.warning('请先登录')
      router.push('/login')
      return
    }

    const response = await request({
      url: '/DeliveryAddressController/getDeliveryAddressById',
      method: 'get',
      headers: {
        'Authorization': token
      },
      params: {
        daId: address.value.daId
      }
    })

    if (response.data) {
      address.value = response.data
    }
  } catch (error) {
    console.error('获取地址信息错误:', error)
    if (error.response?.status === 403) {
      ElMessage.error('登录已过期，请重新登录')
      sessionStorage.removeItem('token')
      sessionStorage.removeItem('user')
      router.push('/login')
    } else {
      ElMessage.error('获取地址信息失败')
    }
  }
}

// 更新地址
const editUserAddress = async () => {
  try {
    const token = sessionStorage.getItem('token')
    if (!token) {
      ElMessage.warning('请先登录')
      router.push('/login')
      return
    }

    // 表单验证
    if (!address.value.contactName) {
      ElMessage.warning('请输入联系人姓名')
      return
    }
    if (!address.value.contactTel) {
      ElMessage.warning('请输入联系电话')
      return
    }
    if (!address.value.address) {
      ElMessage.warning('请输入详细地址')
      return
    }

    const response = await request({
      url: '/DeliveryAddressController/updateDeliveryAddress',
      method: 'put',  // 修改为 PUT 方法
      headers: {
        'Authorization': token,
        'Content-Type': 'application/x-www-form-urlencoded'
      },
      data: {
        daId: address.value.daId,
        contactName: address.value.contactName,
        contactSex: address.value.contactSex,
        contactTel: address.value.contactTel,
        address: address.value.address
      }
    })

    if (response.data === 1) {
      ElMessage.success('修改成功')
      router.back()
    } else {
      ElMessage.error('修改失败')
    }
  } catch (error) {
    console.error('更新地址错误:', error)
    if (error.response?.status === 403) {
      ElMessage.error('登录已过期，请重新登录')
      sessionStorage.removeItem('token')
      sessionStorage.removeItem('user')
      router.push('/login')
    } else {
      ElMessage.error('更新地址失败')
    }
  }
}

onMounted(() => {
  loadAddress()
})
</script>

<style scoped>
.wrapper {
  width: 100%;
  height: 100%;
}

header {
  width: 100%;
  height: 12vw;
  background-color: #0097FF;
  color: #fff;
  font-size: 4.8vw;
  position: fixed;
  left: 0;
  top: 0;
  z-index: 1000;
  display: flex;
  justify-content: center;
  align-items: center;
}

.content {
  margin-top: 12vw;
  padding: 3vw;
}

.content ul li {
  padding: 3vw 0;
  border-bottom: 1px solid #eee;
}

.content ul li p {
  color: #666;
  font-size: 3.5vw;
  margin-bottom: 2vw;
}

.content ul li input[type="text"],
.content ul li input[type="tel"] {
  width: 100%;
  height: 8vw;
  border: 1px solid #ddd;
  border-radius: 1vw;
  padding: 0 2vw;
  font-size: 3.5vw;
  box-sizing: border-box;
}

.sex {
  display: flex;
  gap: 4vw;
}

.sex label {
  display: flex;
  align-items: center;
  font-size: 3.5vw;
  color: #666;
}

.sex input[type="radio"] {
  margin-right: 1vw;
  width: 4vw;
  height: 4vw;
}

.save-btn {
  width: 100%;
  height: 10vw;
  background-color: #0097FF;
  color: white;
  border: none;
  border-radius: 1vw;
  font-size: 4vw;
  margin-top: 6vw;
}
</style>